package com.app.couponsharelife.ui.main.me.team
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.RemoteResultBean
import com.app.couponsharelife.data.bean.UserTeamMemberBean
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.MyTeamListAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.popupwindow.TeamPopupWindow
import com.app.couponsharelife.utils.AppUtils
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_newteam.*
import java.util.HashMap
import com.app.couponsharelife.ui.main.me.invite.ShareInvitePicActivity


/**
 *Created by xct on 2019/3/19
 *Description:我的团队成员列表页面
 */
class NewTeamFragment:LazyFragment(),View.OnClickListener, OnClickListener {
    private var adapter:MyTeamListAdapter?=null
    private var pageIndex=1
    private var type=""
    private var classType="0"  //分类类型
    private var jrsjType="1"  //加入时间排序类型
    private var tdrsType="1" //团队人数排序类型
    private var sxTyep=""
    private var dataList= arrayListOf<UserTeamMemberBean.RecordsBean>()
    private var teamPopupwindow:TeamPopupWindow?=null
    companion object {
        fun newInstance(type: String): NewTeamFragment {
            val bundle=Bundle()
            bundle.putString("type", type)
            val fragment = NewTeamFragment()
            fragment.arguments = bundle
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_newteam

    override fun initViews() {
        type=arguments!!.getString("type", "")
        setRefresh()
        fragNewteam_rv.layoutManager=LinearLayoutManager(context)
        adapter= MyTeamListAdapter(context!!,dataList)
        fragNewteam_rv.adapter=adapter
        fragNewteam_lljrsj.setOnClickListener(this)
        fragNewteam_ivJrsj.setOnClickListener(this)
        fragNewteam_llContent.setOnClickListener {
            startActivity(Intent(context,ShareInvitePicActivity::class.java))
        }
        fragNewteam_lltdrs.setOnClickListener(this)
        fragNewteam_ivTdrs.setOnClickListener(this)

        fragNewteam_lljssx.setOnClickListener(this)
        fragNewteam_ivJssx.setOnClickListener(this)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        val animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        fragNewteam_smartrefresh.setOnMultiPurposeListener(object : OnMultiPurposeListener {
            override fun onFooterMoving(footer: RefreshFooter?, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderStartAnimator(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {

            }

            override fun onFooterReleased(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {

            }

            override fun onHeaderMoving(header: RefreshHeader?, isDragging: Boolean, percent: Float, offset: Int, headerHeight: Int, maxDragHeight: Int) {
                setAnima(percent)
            }

            override fun onFooterFinish(footer: RefreshFooter?, success: Boolean) {

            }

            override fun onFooterStartAnimator(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderReleased(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                animationDrawable.start()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getData(false)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex=1
                getData(true)
            }

            override fun onHeaderFinish(header: RefreshHeader?, success: Boolean) {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable.stop()
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.fragNewteam_lljrsj->{ //加入时间
                if ("0"!=classType) {
                    classType="0"
                    jrsjType="1"
                    tdrsType="1"
                    fragNewteam_tvJrsj.setTextColor(resources.getColor(R.color.red_ff038))
                    fragNewteam_tvTdrs.setTextColor(resources.getColor(R.color.gray_66))
                    fragNewteam_tvJssx.setTextColor(resources.getColor(R.color.gray_66))
                    fragNewteam_ivJrsj.setImageResource(R.drawable.ic_order_down)
                    fragNewteam_ivTdrs.setImageResource(R.drawable.ic_order_down)
                    pageIndex=1
                    fragNewteam_smartrefresh.resetNoMoreData()
                    getData(false)
                }else{
                    if ("0"==jrsjType){
                        jrsjType="1"
                        fragNewteam_ivJrsj.setImageResource(R.drawable.ic_order_down)
                    }else{
                        jrsjType="0"
                        fragNewteam_ivJrsj.setImageResource(R.drawable.ic_order_up)
                    }
                    pageIndex=1
                    fragNewteam_smartrefresh.resetNoMoreData()
                    getData(false)
                }
            }
            R.id.fragNewteam_lltdrs->{  //团队人数
                if ("1"!=classType) {
                    classType="1"
                    jrsjType="1"
                    tdrsType="1"
                    fragNewteam_tvJrsj.setTextColor(resources.getColor(R.color.gray_66))
                    fragNewteam_tvTdrs.setTextColor(resources.getColor(R.color.red_ff038))
                    fragNewteam_tvJssx.setTextColor(resources.getColor(R.color.gray_66))
                    fragNewteam_ivJrsj.setImageResource(R.drawable.ic_order_down)
                    fragNewteam_ivTdrs.setImageResource(R.drawable.ic_order_down)
                    pageIndex=1
                    fragNewteam_smartrefresh.resetNoMoreData()
                    getData(false)
                }else{
                    if ("0"==tdrsType){
                        tdrsType="1"
                        fragNewteam_ivTdrs.setImageResource(R.drawable.ic_order_down)
                    }else{
                        tdrsType="0"
                        fragNewteam_ivTdrs.setImageResource(R.drawable.ic_order_up)
                    }
                    pageIndex=1
                    fragNewteam_smartrefresh.resetNoMoreData()
                    getData(false)
                }
            }
            R.id.fragNewteam_lljssx->{  //角色筛选
                if (teamPopupwindow==null){
                    teamPopupwindow= TeamPopupWindow(context!!,this)
                }
                if (!teamPopupwindow!!.isShowing){
                    //teamPopupwindow!!.showAtLocation(fragNewteam_ivJssx,Gravity.RIGHT,40,0)
                    teamPopupwindow!!.showAsDropDown(fragNewteam_ivJssx,40,0)
                }
            }
        }
    }
    override fun click(arg1: Int, arg2: Any) {
        if ("2"!=classType) {
            classType="2"
            jrsjType="1"
            tdrsType="1"
            fragNewteam_tvJrsj.setTextColor(resources.getColor(R.color.gray_66))
            fragNewteam_tvTdrs.setTextColor(resources.getColor(R.color.gray_66))
            fragNewteam_tvJssx.setTextColor(resources.getColor(R.color.red_ff038))
            fragNewteam_ivJrsj.setImageResource(R.drawable.ic_order_down)
            fragNewteam_ivTdrs.setImageResource(R.drawable.ic_order_down)
        }
        when(arg1){
            0->{
                if (teamPopupwindow!!.isShowing){
                    teamPopupwindow!!.dismiss()
                }
                pageIndex=1
                sxTyep=""
                fragNewteam_smartrefresh.resetNoMoreData()
                getData(false)
            }
            1->{
                if (teamPopupwindow!!.isShowing){
                    teamPopupwindow!!.dismiss()
                }
                pageIndex=1
                sxTyep="1"
                fragNewteam_smartrefresh.resetNoMoreData()
                getData(false)
            }
            2->{
                if (teamPopupwindow!!.isShowing){
                    teamPopupwindow!!.dismiss()
                }
                pageIndex=1
                sxTyep="2"
                fragNewteam_smartrefresh.resetNoMoreData()
                getData(false)
            }
        }
    }
    override fun lazyLoad() {
        getData(false)
    }
    private fun getData(isRefresh:Boolean){
        if (!isRefresh&&pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map= HashMap<String,String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["pageNo"] = pageIndex.toString()
        map["pageSize"] = "15"
        map["type"] = type  //类型-null(全部),DIRECTLY_UNDER(直属), RECOMMEND(推荐)
        map["searchType"] = classType  //查看类型 默认所有 0.按时间查询 1.按团队人数 2.按角色
        map["timeType"] = jrsjType  //加入时间排序 0.正序 1.倒序 默认逆序
        map["juniorType"] = tdrsType  //团队人数排序 0.正序 1.逆序 默认逆序
        map["levelType"] = sxTyep  //角色筛选 默认查看全部 1.查看普通用户 2.查看高级用户
        RetrofitWorker.retrofitWorker.getUserTeamList(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<UserTeamMemberBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<UserTeamMemberBean>) {
                        if (it.code==200&&it.data!=null){
                            if (!isRefresh&&pageIndex==1){
                                dataList.clear()
                                dismissProgressDialog()
                            }
                            if (it.data!=null&&it.data!!.records!!.isNotEmpty()){
                                if (pageIndex==1){
                                    dataList.clear()
                                    fragNewteam_llerror.visibility= View.GONE
                                    fragNewteam_rv.visibility= View.VISIBLE
                                    if (isRefresh){
                                        fragNewteam_smartrefresh.finishRefresh()
                                    }
                                }else{
                                    fragNewteam_smartrefresh.finishLoadMore()
                                }
                                dataList.addAll(it.data!!.records!!)
                                if (it.data!!.records!!.size<10){
                                    val recordsBean=UserTeamMemberBean.RecordsBean()
                                    recordsBean.grade=""
                                    dataList.add(recordsBean)
                                    fragNewteam_smartrefresh.finishLoadMoreWithNoMoreData()
                                }
                                pageIndex++
                                adapter!!.notifyDataSetChanged()
                            }else{
                                if (isRefresh){
                                    fragNewteam_smartrefresh.finishRefresh()
                                }
                                if (pageIndex==1&&dataList.size==0){
                                    fragNewteam_smartrefresh.finishLoadMoreWithNoMoreData()
                                    fragNewteam_llerror.visibility= View.VISIBLE
                                    fragNewteam_rv.visibility= View.GONE
                                }
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            fragNewteam_smartrefresh.finishRefresh()
                        }
                        if (pageIndex>1){
                            fragNewteam_smartrefresh.finishLoadMore()
                        }
                        if (pageIndex==1){
                            fragNewteam_smartrefresh.finishLoadMoreWithNoMoreData()
                            fragNewteam_llerror.visibility= View.VISIBLE
                            fragNewteam_rv.visibility= View.GONE
                        }
                        if (e is OtherException){
                            //showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                        }
                    }
                })
    }
}